package com.achievo.know.job;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.achievo.know.component.impl.FileManagerConfig;
import com.achievo.know.pojo.Constants;

public class BackupDbJob {
	
	@Autowired
	private FileManagerConfig config;
	public void setConfig(FileManagerConfig config) {
		this.config = config;
	}

	public void work() {
		Date td=new Date();
		Date outd=DateUtils.addMonths(td, -3);
		System.out.println("任务调度:备份数据库 "+DateFormatUtils.format(td, "yyyy-MM-dd HH:mm"));
		String jdbc_url=config.getConfigHolder().getConfig(
				Constants.JDBC_URL);
		String jdbc_username=config.getConfigHolder().getConfig(
				Constants.JDBC_USERNAME);
		String jdbc_password=config.getConfigHolder().getConfig(
				Constants.JDBC_PASSWORD);
		String outputFile=config.getBackupDbStoreDirectory();
		
		//先删除过期的
		File dbDirectory=new File(outputFile);
		if(dbDirectory.exists()){
			File[] pdfs=dbDirectory.listFiles();
			for(File z:pdfs){
				String name=FilenameUtils.getBaseName(z.getName());
				try {
					Date nameDate=DateUtils.parseDate(name, new String[]{"yyyyMMddHHmm"});
					if(nameDate.before(outd)){
						System.out.println("delete backup "+name);
						delete(z);
					}
				} catch (Exception e) {

				}
			}
		}
		//开始备份
		String host, port;
		host=jdbc_url.split(":")[2].replaceAll("//", "");
		String temp=jdbc_url.split(":")[3].replaceAll("//", "").split("\\?")[0];
		port=temp.split("\\/")[0];
		String db=temp.split("\\/")[1];
		String filename=outputFile+File.separator+DateFormatUtils.format(td, "yyyyMMddHHmm")+".bak";
		BackupUtils.backupMySQL(host, port, jdbc_username, jdbc_password, db, filename, true);
	}

    public static void main(String[] args){
        File f=new File("C:\\img-228184245.pdf");
        delete(f);
    }

    static void delete(File f){
        try {
            FileUtils.forceDelete(f);;
        } catch (Exception e) {
            try {
                Process run = Runtime.getRuntime().exec("cmd /c Del "+f.getAbsolutePath());
                int exitVal = run.waitFor();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }
}
